package mms

import java.text.DecimalFormat;
//定时处理jms上传上来的 xml文件
class JmsJob {
    def timeout = 1000l * 30 // execute job once in 5 seconds

//    static triggers = {
//        simple name:'simpleTrigger', startDelay:10000, repeatInterval: 30000, repeatCount: 10
//        cron name:'cronTrigger', startDelay:10000, cronExpression: '0/6 * 15 * * ?'
//        custom name:'customTrigger', triggerClass:MyTriggerClass, myParam:myValue, myAnotherParam:myAnotherValue
//    }

    def  concurrent  = false
    //def log
    def grailsApplication


    def execute() {
        // execute task
        println "message process start..."
        //println "123456".encodeAsMD5()
        println "1 - start process"
        process()
        println "2 - start processfoods"
        processfoods()
        println "3 - start catchProcess"

        catchProcess()
        println "4 - start errorProcess"
        errorProcess()
        println "message process complete"
        System.gc()
        
    }

    // 胡，13991322373
    // 检查是否有这个药品，没有新建
    def checkMedicine = { production , company ->
        
        def  prod  
        if (company) {
               prod = Medicine.findByProductionAndCompany(production , company)
               if (!prod) {
                   prod = new Medicine(production : production , company : company)
               }
               return prod
        } 
        //return null; 
    }

    /// 处理药品实时数据的进程
    def process = { 

        def out = new File("c:\\exce.txt")
        def exce = []
        out.eachLine{
            exce.add(it)
        }
        DecimalFormat decimalformat = new DecimalFormat("###,###.####");
     

        def sFile  = new File(grailsApplication.config?.grails?.jms.receive); 
        searchInputFile(sFile , ~/data.*\.(xml)$/ ){filename ->
            def xmldata = [] 
            def xmlparser = new XmlParser().parse(filename)
         
            xmlparser.product.each { dom ->
                
                 def name = dom.get('name').text()?.trim().replace("\n","").replace("\t","")
                 def enterprise = dom.get('enterprise').text()?.trim().replace("\n","").replace("\t","")
                 def sell =  dom.get('sell').text()?.trim().replace("\n","").replace("\t","")
 
                 def company = MedicineCompany.findByName(enterprise + sell) 
             
                 if (company  && name.trim() != "" ) {
                      
                // 检查是否有这个药品，没有新建
                 def medicine = checkMedicine( name , company)

                 if (medicine) {
                  //  log.info "medicine.version = ${medicine.version}"
                    if (!medicine.version) { // == null 是新对象
                        medicine.dosage =  dom.get('dosage').text()?.trim()
                        medicine.manufacturer =  dom.get('manufacturer').text()?.trim()
                        medicine.approvalNumber =  dom.get('approvalnumber').text()?.trim()
                        medicine.save(flush:true)
                     }
                        def retail = new MedicineRetail(medicine : medicine , company : company)
                      
                        retail.validity = dom.get('validity').text().trim()?.trim()
                        retail.department  = dom.get('sell').text()?.trim()
                        retail.purchase = dom.get('purchase').text()?.trim()
                        retail.batchNumber = dom.get('batchnumber').text()?.trim()
                        retail.publish = dom.get('publish').text()?.trim()

  
                        def amount = dom.get('sellamount').text()?.trim()
                        def inmount = dom.get('inmount').text()?.trim()

                        // inmount 字段如果有内容就是 购进入库
                        if (inmount && inmount != "" ){
                            retail.retail = MedicineRetail.BUY
                            amount = inmount
                        }
                        if ( amount && amount != "" ) {
                             retail.amount = decimalformat.parse(amount)
                           
                             if (!retail.save()) {
                                 retail.errors.each{
                                    println it
                                 }
                             }
                        } 
                    }
                 }else{
                            def pass = true
                            if (name=="" || sell==""  || enterprise=="") {
                                pass = false
                            }

                            pass = !exce.any{ elem -> 
                                elem == enterprise + sell
                            }

                            if (pass) {
                                
                           
                            def obj = [:]
                            obj.name = name
                            obj.dosage = (dom.get('dosage').text()?.trim())
                            obj.manufacturer = (dom.get('manufacturer').text()?.trim())
                            obj.batchnumber = (dom.get('batchnumber').text()?.trim())
                            obj.approvalnumber = (dom.get('approvalnumber').text()?.trim())
                            obj.validity = (dom.get('validity').text()?.trim())
                            obj.purchase = (dom.get('purchase').text()?.trim())
                            obj.sellamount = (dom.get('sellamount').text()?.trim())
                            obj.inmount = (dom.get('inmount').text()?.trim())
                            obj.publish = (dom.get('publish').text()?.trim())
                            obj.sell = sell
                            obj.enterprise = enterprise
                            xmldata.add(obj)

                            
//                            纪录没有对应企业的信息
                            File jmslastent = new File("c:\\jmslastent.txt")
                            jmslastent.append("${obj.enterprise} - ${obj.sell}\n");
                            }
                       
                 }
           
            }//end xmldom
            if (xmldata.size() > 0) {

  
                            def builder = new groovy.xml.StreamingMarkupBuilder()
                            builder.encoding = "gb2312"
                            def xmlbuilder = {
                              mkp.xmlDeclaration()
                                   elink{
                                        xmldata.each{ xmlproduct ->
                                             product{  
                                                name("${xmlproduct?.name}")
                                                dosage("${xmlproduct?.dosage}")
                                                manufacturer("${xmlproduct?.manufacturer}")
                                                batchnumber("${xmlproduct?.batchnumber}")
                                                approvalnumber("${xmlproduct?.approvalnumber}")
                                                validity("${xmlproduct?.validity}")
                                                purchase("${xmlproduct?.purchase}")
                                                sellamount("${xmlproduct?.sellamount}")
                                                inmount("${xmlproduct?.inmount}")
                                                publish("${xmlproduct?.publish}")
                                                sell("${xmlproduct?.sell}")
                                                enterprise("${xmlproduct?.enterprise}")
                                             }
                                         }
                                  }
                            }
 

                new File(filename).withWriter('gb2312'){ w->
                  w<<  builder.bind(xmlbuilder)
                  w.close()
                }
                xmldata.clear() 
                xmldata = null

                moveFile(filename)
                builder = null
            }else{
                deleteFile(filename)
            }
            xmlparser = null
        } 
    }


    def processfoods = {
        def sFile  = new File(grailsApplication.config?.grails?.jms.receive); 
        searchInputFile(sFile , ~/food.*\.(xml)$/ ){filename ->
        DecimalFormat decimalformat = new DecimalFormat("###,###.####");


            def xmldata = []  //保存没有处理的xml数据
            def xmlparser = new XmlParser().parse(filename)
         
            xmlparser.product.each { dom ->
                  
                 def name = dom.get('name').text()?.trim().replace("\n","").replace("\t","")
                 def enterprise = dom.get('enterprise').text()?.trim().replace("\n","").replace("\t","")
          
                 def company = RestaurantCompany.findByName(enterprise) 
             
                 if (company  && name.trim() != "" ) {
   
 
                        def retail = new FoodRetail(name : name , enterprise : company)
                        def amount = dom.get('amount').text()?.trim()
                      
                        retail.specifications = dom.get('specifications').text().trim()?.trim()

                        if (amount && amount != "") {
                           retail.amount  = decimalformat.parse(amount) 
                        }
                        
                        retail.purchasetime = dom.get('purchasetime').text()?.trim()
                        retail.supplier = dom.get('supplier').text()?.trim()
                        retail.contactsupplier = dom.get('contactsupplier').text()?.trim()
                        retail.consistent = dom.get('consistent').text()?.trim()
                        retail.acceptpeople = dom.get('acceptpeople').text()?.trim()
                        retail.pushintime = dom.get('pushintime').text()?.trim()
 
                        if (!retail.save(flush:true) ) {
                            retail.errors.each{
                                println  it
                            }

                        }
                       
                  
                 }else{
                            def pass = true
                            if (name==""  || enterprise=="") {
                                pass = false
                            }
  
                            if (pass) {
                               
                       
                           
                                def obj = [:]
                                obj.name = name
                                obj.specifications = (dom.get('specifications').text()?.trim())
                                obj.amount = (dom.get('amount').text()?.trim())
                                obj.purchasetime = (dom.get('purchasetime').text()?.trim())
                                obj.supplier = (dom.get('supplier').text()?.trim())
                                obj.contactsupplier = (dom.get('contactsupplier').text()?.trim())
                                obj.consistent = (dom.get('consistent').text()?.trim())
                                obj.acceptpeople = (dom.get('acceptpeople').text()?.trim())
                                obj.enterprise = enterprise
                                obj.pushintime = (dom.get('pushintime').text()?.trim())
             
                                xmldata.add(obj)

                            
//                            纪录没有对应企业的信息
                            File jmslastent = new File("c:\\foodjmslastent.txt")
                                jmslastent.append("${obj.enterprise} - ${obj.sell}\n");
                            }
                       
                 }
           
            }//end xmldom
            if (xmldata.size() > 0) {

        //  <name>韭黄</name>
//    <specifications>斤</specifications>
//    <amount>2</amount>
//    <purchasetime>2011-04-01</purchasetime>
//    <supplier>天启蔬菜配送公司</supplier>
//    <contactsupplier>13572282567</contactsupplier>
//    <consistent>是</consistent>
//    <c>王婷</acceptpeople>
//    <enterprise>灿烂阳光酒店</enterprise>
//    <pushintime>2011-04-14 9:40:16</pushintime>  

                            def builder = new groovy.xml.StreamingMarkupBuilder()
                            builder.encoding = "gb2312"
                            def xmlbuilder = {
                              mkp.xmlDeclaration()
                                   elink{
                                        xmldata.each{ xmlproduct ->
                                             product{  
                                                name("${xmlproduct?.name}")
                                                specifications("${xmlproduct?.specifications}")
                                                amount("${xmlproduct?.amount}")
                                                purchasetime("${xmlproduct?.purchasetime}")
                                                supplier("${xmlproduct?.supplier}")
                                                contactsupplier("${xmlproduct?.contactsupplier}")
                                                consistent("${xmlproduct?.consistent}")
                                                acceptpeople("${xmlproduct?.acceptpeople}")
                                                enterprise("${xmlproduct?.enterprise}")
                                                pushintime("${xmlproduct?.pushintime}")
                                              
                                             }
                                         }
                                  }
                            }
 

                new File(filename).withWriter('gb2312'){ w->
                  w<<  builder.bind(xmlbuilder)
                  w.close()
                }
                xmldata.clear() 
                xmldata = null

                moveFile(filename)
                builder = null
            }else{
                deleteFile(filename)
            }
            xmlparser = null 
        }
 
    }
 
 
    def  catchProcess = {
        def sFile  = new File(grailsApplication.config?.grails?.jms.receive); 
        searchInputFile(sFile , ~/catch.*\.(xml)$/ ){filename ->
            deleteFile(filename)
 
        }
    }

    def  errorProcess = {
        def sFile  = new File(grailsApplication.config?.grails?.jms.receive); 
        searchInputFile(sFile , ~/error.*\.(xml)$/ ){filename ->
            deleteFile(filename)
 
        }
    }


// 处理目录中的所有文件
    def searchInputFile(inputFile, filePattern , closure ){  
        //def filePattern = ~/data.*\.(xml)$/
        if(inputFile.isDirectory()){
            
            inputFile.eachFile{  fileRecurse -> //  递归获得所有目录和文件
                if(!fileRecurse.isDirectory() ){ 
                    if ( fileRecurse.getName() =~ filePattern   ) { 
                          println  "searchInputFile : ${fileRecurse.absolutePath}"
                          def start = System.currentTimeMillis()
                          try {
                              closure.call( fileRecurse.absolutePath  )
                          }
                          catch (ex) {
                              println ex
                          }
                          finally {
                              
                          } 
                          println "file each process time : ${System.currentTimeMillis() - start}"  
                    } 
                } 
            }
        }
    }

    def moveFile = {filename -> 
            def file = new File(filename)
            if (file.exists()) { 
               def tofile = filename.replace("rcvfiles","done")
               def to = new File(tofile)
               if (to.exists()) {
                   to.delete()
               }
               file.renameTo(to)
               log.info "move file = ${filename}"
            }
    }

    def deleteFile = {filename -> 
            def file = new File(filename)
            if (file.exists()) {
               file.delete() 
               log.info "delete file = ${filename}"
            }
    }

}
 